package controllers

import (
	"context"
	"dataflow-operator/command"

	"github.com/go-logr/logr"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"

	corev1 "k8s.io/api/core/v1"
	//dfv1 "dataflow-operator/api/v1"
)

// ConfigReconciler reconciles a Pod object
type ConfigReconciler struct {
	client.Client
	Logger logr.Logger
}

//+kubebuilder:rbac:groups=core,resources=configmaps,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=core,resources=configmaps/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=core,resources=configmaps/finalizers,verbs=update

// https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.8.3/pkg/reconcile
func (r *ConfigReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	// ==================your logic here=====================
	var conf corev1.ConfigMap
	client := r.Client

	if err := client.Get(ctx, req.NamespacedName, &conf); err != nil {
		r.Logger.Error(err, "Can't get configmap")
	} else {
		if conf.Name == "dataflow-operator" {
			r.Logger.Info("Get configmap update", "configmap name", conf.GetName())
			command.DataflowConfigChannel <- &conf
		}
	}

	return ctrl.Result{}, nil
}

// SetupWithManager sets up the controller with the Manager.
func (r *ConfigReconciler) SetupWithManager(mgr ctrl.Manager) error {
	return ctrl.NewControllerManagedBy(mgr).
		For(&corev1.ConfigMap{}).
		Complete(r)
}
